package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.service.impl.UserServiceImpl;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Api(tags = "用户模块")
@RequestMapping("/user/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private JwtProperties jwtProperties;
    private final String secret = "hui";
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO dto) {
        //调用service层，返回user对象（包含openid，id等信息)
        User user = userServiceImpl.login(dto);
        log.info("user:{}",user);
        log.info("usertokenname:{}",jwtProperties.getUserTokenName());
        //根据user对象生成map
        HashMap<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        log.info("登陆时，生成的claims：{}",claims);
        //根据openid生成令牌，返回结果携带令牌
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO VO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        log.info("VO:{}",VO);
        return Result.success(VO);
    }
}